
const express = require('express');
const router = express.Router();
const multer = require('multer');
const fs = require('fs');

let uploadFileName = 'public/my-uploads';
if(fs.existsSync(uploadFileName)){
  console.log('1');
}else{
  fs.mkdirSync(uploadFileName)
}
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, uploadFileName)
  },
  filename: function (req, file, cb) {
    console.log(req.body);
    let arr = file.originalname.split('.');
    let exc = arr[arr.length - 1];
    cb(null, file.fieldname + '-' + Date.now() + Math.floor(Math.random() * 1000) + '.' + exc)
  }
})

const upload = multer({ storage: storage })


router.post('/upload',upload.single('avator'),(req,res) => {
  console.log(req.file);
  const fileUrl = 'localhost:3000/my-uploads/' + req.file.filename;
  res.json({
    data:fileUrl
  })
})
router.post('/mul',upload.array('mul'),(req,res) => {
  console.log(req.files);
  const fileUrl = [];

  req.files.forEach(element => {
    fileUrl.push('localhost:3000/my-uploads/' + element.filename)
  });
  res.json({
    data:fileUrl
  })
})

module.exports = router
